import * as THREE from 'three';
import { Vec3 } from '@/core/types';
import { Entity } from '@/entities/Entity';

/**
 * 玩家战斗系统 - 处理玩家攻击生物的逻辑
 */
export class PlayerCombat {
  private camera: THREE.PerspectiveCamera;
  private raycaster: THREE.Raycaster;
  private attackRange = 4; // 攻击距离
  private attackCooldown = 0;
  private attackInterval = 0.6; // 攻击间隔
  private attackDamage = 5; // 基础攻击伤害

  constructor(camera: THREE.PerspectiveCamera) {
    this.camera = camera;
    this.raycaster = new THREE.Raycaster();
  }

  /**
   * 执行攻击
   */
  public performAttack(entities: Entity[]): Entity | null {
    if (this.attackCooldown > 0) {
      return null;
    }

    const targetEntity = this.getTargetEntity(entities);
    if (targetEntity) {
      // 造成伤害
      targetEntity.takeDamage(this.attackDamage);
      
      // 设置攻击冷却
      this.attackCooldown = this.attackInterval;
      
      console.log(`Player attacked ${targetEntity.getType()} for ${this.attackDamage} damage!`);
      
      return targetEntity;
    }

    return null;
  }

  /**
   * 获取攻击目标
   */
  private getTargetEntity(entities: Entity[]): Entity | null {
    const direction = new THREE.Vector3();
    this.camera.getWorldDirection(direction);
    
    this.raycaster.set(this.camera.position, direction);

    let closestEntity: Entity | null = null;
    let closestDistance = this.attackRange;

    for (const entity of entities) {
      if (!entity.isAlive()) continue;

      const entityMesh = entity.getMesh();
      if (!entityMesh) continue;

      // 计算到实体的距离
      const entityPosition = entity.getPosition();
      const distance = this.camera.position.distanceTo(
        new THREE.Vector3(entityPosition.x, entityPosition.y + 1, entityPosition.z)
      );

      if (distance <= this.attackRange) {
        // 检查是否在攻击方向上
        const toEntity = new THREE.Vector3(
          entityPosition.x - this.camera.position.x,
          entityPosition.y + 1 - this.camera.position.y,
          entityPosition.z - this.camera.position.z
        ).normalize();

        const dot = direction.dot(toEntity);
        
        // 如果角度合适且距离最近
        if (dot > 0.8 && distance < closestDistance) {
          closestEntity = entity;
          closestDistance = distance;
        }
      }
    }

    return closestEntity;
  }

  /**
   * 更新攻击冷却
   */
  public update(deltaTime: number): void {
    if (this.attackCooldown > 0) {
      this.attackCooldown -= deltaTime;
    }
  }

  /**
   * 检查是否可以攻击
   */
  public canAttack(): boolean {
    return this.attackCooldown <= 0;
  }

  /**
   * 设置攻击伤害
   */
  public setAttackDamage(damage: number): void {
    this.attackDamage = damage;
  }

  /**
   * 获取攻击伤害
   */
  public getAttackDamage(): number {
    return this.attackDamage;
  }
}